package modules.arc.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import luxing.common.controller.BaseController;
import luxing.exception.BusinessException;
import luxing.hibernate.CriteriaQuery;
import luxing.util.CriteriaQueryUtil;
import luxing.util.ValidatorUtil;
import luxing.web.model.DataGrid;
import luxing.web.model.Result;
import luxing.web.model.ValidResult;
import modules.arc.entity.ArcExt;
import modules.arc.entity.Driver;
import modules.arc.entity.DriverExt;
import modules.arc.entity.Vehicle;
import modules.arc.service.ArcExtService;
import modules.arc.service.DriverService;
import modules.arc.service.VehicleService;
import modules.sys.entity.Log;
import modules.sys.service.LogService;

/**
 * 
 * @author zzc
 *
 */
@Controller
@RequestMapping("/driverController")
public class DriverController extends BaseController {

	private static final Logger logger = Logger.getLogger(DriverController.class);

	@Autowired
	private LogService logService;
	@Autowired
	private DriverService driverService;
	@Autowired
	private VehicleService vehicleService;
	@Autowired
	private ArcExtService arcExtService;

	/**
	 * 列表页面
	 * 
	 * @return
	 */
	@RequestMapping(params = "index")
	public ModelAndView index(HttpServletRequest request) {
		return new ModelAndView("modules/arc/driver-list");
	}

	/**
	 * 选择页面
	 * 
	 * @return
	 */
	@RequestMapping(params = "selectMore")
	public ModelAndView selectMore(HttpServletRequest request) {
		request.setAttribute("driverId", request.getParameter("driverId"));
		request.setAttribute("driverName", request.getParameter("driverName"));
		return new ModelAndView("modules/arc/driver-selectMore");
	}

	/**
	 * 列表数据
	 * 
	 * @param driver
	 * @param request
	 * @param response
	 * @param dataGrid
	 */
	@RequestMapping(params = "list")
	public void list(Driver driver, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		try {
			CriteriaQuery cq = new CriteriaQuery(Driver.class, dataGrid);
			CriteriaQueryUtil.assembling(cq, driver, request.getParameterMap());
			// 状态
			String status = request.getParameter("status");
			status = StringUtils.isBlank(status) ? Driver.STATUS_ENABLE : status;
			cq.eq("status", status);
			cq.add();
			driverService.listByPage(cq, true);
			listView(response, dataGrid);
		} catch (Exception e) {
			logger.error("司机查询失败", e);
			throw new BusinessException("司机查询失败", e);
		}
	}

	/**
	 * 司机-车辆列表数据
	 * 
	 * @param vehicle
	 * @param request
	 * @param response
	 * @param dataGrid
	 */
	@RequestMapping(params = "driverVehicleList")
	public void driverVehicleList(Vehicle vehicle, HttpServletRequest request, HttpServletResponse response,
			DataGrid dataGrid) {
		try {
			CriteriaQuery cq = new CriteriaQuery(Vehicle.class, dataGrid);
			CriteriaQueryUtil.assembling(cq, vehicle, request.getParameterMap());
			if (StringUtils.isNotBlank(request.getParameter("driverId"))) {
				cq.createAlias("driverList", "drivers");
				cq.eq("drivers.id", request.getParameter("driverId"));
			}
			cq.add();
			vehicleService.listByPage(cq, true);
			listView(response, dataGrid);
		} catch (Exception e) {
			logger.error("车辆查询失败", e);
			throw new BusinessException("车辆查询失败", e);
		}
	}

	/**
	 * 司机-车辆绑定列表数据
	 * 
	 * @param vehicle
	 * @param request
	 * @param response
	 * @param dataGrid
	 */
	@RequestMapping(params = "driverVehicleBindList")
	public void driverVehicleBindList(Vehicle vehicle, HttpServletRequest request, HttpServletResponse response,
			DataGrid dataGrid) {
		try {
			CriteriaQuery cq = new CriteriaQuery(Vehicle.class, dataGrid);
			CriteriaQueryUtil.assembling(cq, vehicle, request.getParameterMap());
			// 状态
			String status = request.getParameter("status");
			if (StringUtils.isBlank(status)) {
				cq.notEq("status", Vehicle.STATUS_DISABLE);
			}
			cq.add();
			vehicleService.listByPage(cq, true);
			listView(response, dataGrid);
		} catch (Exception e) {
			logger.error("车辆查询失败", e);
			throw new BusinessException("车辆查询失败", e);
		}
	}

	/**
	 * 司机-车辆列表页面
	 * 
	 * @return
	 */
	@RequestMapping(params = "driverVehicleIndex")
	public ModelAndView driverVehicleIndex(HttpServletRequest request) {
		request.setAttribute("driverId", request.getParameter("driverId"));
		return new ModelAndView("modules/arc/driverVehicle-list");
	}

	/**
	 * 增加页面
	 * 
	 * @return
	 */
	@RequestMapping(params = "goAdd")
	public ModelAndView goAdd(HttpServletRequest req) {
		return new ModelAndView("modules/arc/driver-add");
	}

	/**
	 * 司机-车辆绑定页面
	 * 
	 * @return
	 */
	@RequestMapping(params = "goBind")
	public ModelAndView goBind(HttpServletRequest req) {
		return new ModelAndView("modules/arc/driverVehicle-bind");
	}

	/**
	 * 修改页面
	 * 
	 * @return
	 */
	@RequestMapping(params = "goUpdate")
	public ModelAndView goUpdate(Driver driver, HttpServletRequest req) {
		if (StringUtils.isNotBlank(driver.getId())) {
			driver = driverService.get(Driver.class, driver.getId());
			req.setAttribute("driverPage", driver);
		}
		return new ModelAndView("modules/arc/driver-update");
	}

	/**
	 * 详情页面
	 * 
	 * @return
	 */
	@RequestMapping(params = "goDetail")
	public ModelAndView goDetail(Driver driver, HttpServletRequest req) {
		if (StringUtils.isNotBlank(driver.getId())) {
			driver = driverService.get(Driver.class, driver.getId());
			req.setAttribute("driverPage", driver);
		}
		return new ModelAndView("modules/arc/driver-update");
	}

	/**
	 * 扩展信息
	 * 
	 * @return
	 */
	@RequestMapping(params = "ext")
	public ModelAndView ext(Driver driverEntity, HttpServletRequest req) {
		req.setAttribute("id", req.getParameter("id"));
		return new ModelAndView("modules/arc/driver-ext");
	}

	/**
	 * 增加
	 * 
	 * @param driver
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "doAdd")
	@ResponseBody
	public Result doAdd(Driver driver, HttpServletRequest request) {
		String msg = null;
		try {
			driver.setStatus(Driver.STATUS_ENABLE);
			// bean校验
			msg = ValidatorUtil.validate(driver);
			if (StringUtils.isNotBlank(msg)) {
				return Result.error(msg);
			}
			driverService.save(driver, arcExtService.listByType(ArcExt.TYPE_DRIVER), request);
			msg = "司机\"" + driver.getName() + "\"增加成功";
			logger.info(msg);
			logService.addLogInfo(msg, Log.OPERATE_ADD);
		} catch (Exception e) {
			msg = "司机\"" + driver.getName() + "\"增加失败";
			logger.error(msg, e);
			throw new BusinessException(msg, e);
		}
		return Result.success(msg);
	}

	/**
	 * 司机-车辆绑定
	 * 
	 * @param req
	 * @return
	 */
	@RequestMapping(params = "doBind")
	@ResponseBody
	public Result doBind(HttpServletRequest req) {
		String msg = null;
		try {
			String vehicleIds = req.getParameter("vehicleIds");
			if (StringUtils.isNotBlank(vehicleIds)) {
				for (String vehicleId : vehicleIds.split(",")) {
					Vehicle vehicle = vehicleService.get(Vehicle.class, vehicleId);
					Driver driver = new Driver();
					driver.setId(req.getParameter("driverId"));
					Map<String, Driver> driverMap = new HashMap<String, Driver>();
					driverMap.put(req.getParameter("driverId"), driver);
					if (CollectionUtils.isNotEmpty(vehicle.getDriverList())) {
						for (Driver entity : vehicle.getDriverList()) {
							driverMap.put(entity.getId(), entity);
						}
					}
					List<Driver> driverList = new ArrayList<Driver>(driverMap.values());
					vehicle.setDriverList(driverList);
					vehicleService.saveOrUpdate(vehicle);
				}
			}
			msg = "司机-车辆,绑定成功";
			logger.info(msg);
			logService.addLogInfo(msg, Log.OPERATE_UPDATE);
		} catch (Exception e) {
			msg = "司机-车辆,绑定失败";
			logger.error(msg, e);
			throw new BusinessException(msg, e);
		}
		return Result.success(msg);
	}

	/**
	 * 司机-车辆取消绑定
	 * 
	 * @param req
	 * @return
	 */
	@RequestMapping(params = "doCancelBind")
	@ResponseBody
	public Result doCancelBind(HttpServletRequest req) {
		String msg = null;
		try {
			String vehicleId = req.getParameter("vehicleId");
			String driverId = req.getParameter("driverId");
			Vehicle vehicle = vehicleService.get(Vehicle.class, vehicleId);
			Iterator<Driver> iterator = vehicle.getDriverList().iterator();
			while (iterator.hasNext()) {
				if (iterator.next().getId().equals(driverId)) {
					iterator.remove();
					break;
				}
			}
			vehicleService.saveOrUpdate(vehicle);
			msg = "司机-车辆,取消绑定成功";
			logger.info(msg);
			logService.addLogInfo(msg, Log.OPERATE_UPDATE);
		} catch (Exception e) {
			msg = "司机-车辆,取消绑定失败";
			logger.error(msg, e);
			throw new BusinessException(msg, e);
		}
		return Result.success(msg);
	}

	/**
	 * 修改
	 * 
	 * @param driver
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "doUpdate")
	@ResponseBody
	public Result doUpdate(Driver driver, HttpServletRequest request) {
		String msg = null;
		try {
			// 档案扩展
			List<ArcExt> arcExtList = arcExtService.listByType(ArcExt.TYPE_DRIVER);
			List<DriverExt> driverExtList = new ArrayList<DriverExt>();
			for (ArcExt arcExt : arcExtList) {
				String value = request.getParameter(arcExt.getId());
				if (StringUtils.isNotBlank(value)) {
					DriverExt driverExt = new DriverExt();
					driverExt.setDriverId(driver.getId());
					driverExt.setArcExtId(arcExt.getId());
					driverExt.setValue(value);
					driverExtList.add(driverExt);
				}
			}
			driverService.update(driver, driverExtList);
			msg = "司机\"" + driver.getName() + "\"修改成功";
			logger.info(msg);
			logService.addLogInfo(msg, Log.OPERATE_UPDATE);
		} catch (Exception e) {
			msg = "司机\"" + driver.getName() + "\"修改失败";
			logger.error(msg, e);
			throw new BusinessException(msg, e);
		}
		return Result.success(msg);
	}

	/**
	 * 删除
	 * 
	 * @return
	 */
	@RequestMapping(params = "doDel")
	@ResponseBody
	public Result doDel(Driver driver, HttpServletRequest request) {
		String msg = null;
		try {
			driver = driverService.get(Driver.class, driver.getId());
			driverService.delete(driver);
			msg = "司机\"" + driver.getName() + "\"删除成功";
			logger.info(msg);
			logService.addLogInfo(msg, Log.OPERATE_DEL);
		} catch (Exception e) {
			msg = "司机\"" + driver.getName() + "\"删除失败";
			logger.error(msg, e);
			throw new BusinessException(msg, e);
		}
		return Result.success(msg);
	}

	/**
	 * 姓名校验
	 */
	@RequestMapping(params = "validName")
	@ResponseBody
	public ValidResult validName(HttpServletRequest request) {
		ValidResult result = new ValidResult();
		String id = request.getParameter("id");
		String name = request.getParameter("name");
		Driver driver = driverService.getByName(name);
		if (id == null) {
			// 增加
			if (driver != null) {
				result.setInfo("姓名已存在");
				result.setStatus("n");
			}
		} else {
			// 修改
			if (driver != null && !driver.getId().equals(id)) {
				result.setInfo("姓名已存在");
				result.setStatus("n");
			}
		}
		return result;
	}

	/**
	 * 手机校验
	 */
	@RequestMapping(params = "validPhone")
	@ResponseBody
	public ValidResult validPhone(HttpServletRequest request) {
		ValidResult result = new ValidResult();
		String id = request.getParameter("id");
		String phone = request.getParameter("phone");
		Driver driver = driverService.getByPhone(phone);
		if (id == null) {
			// 增加
			if (driver != null) {
				result.setInfo("手机已存在");
				result.setStatus("n");
			}
		} else {
			// 修改
			if (driver != null && !driver.getId().equals(id)) {
				result.setInfo("手机已存在");
				result.setStatus("n");
			}
		}
		return result;
	}

	/**
	 * 身份证校验
	 */
	@RequestMapping(params = "validIdCard")
	@ResponseBody
	public ValidResult validIdCard(HttpServletRequest request) {
		ValidResult result = new ValidResult();
		String id = request.getParameter("id");
		String idCard = request.getParameter("idCard");
		Driver driver = driverService.getByIdCard(idCard);
		if (id == null) {
			// 增加
			if (driver != null) {
				result.setInfo("身份证已存在");
				result.setStatus("n");
			}
		} else {
			// 修改
			if (driver != null && !driver.getId().equals(id)) {
				result.setInfo("身份证已存在");
				result.setStatus("n");
			}
		}
		return result;
	}

}
